package x.ovo.wechat.bot.plugin;

import lombok.NonNull;
import x.ovo.wechat.bot.core.contact.Contactable;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.event.MessageEvent;
import x.ovo.wechat.bot.core.message.EmoteMessage;
import x.ovo.wechat.bot.core.message.Message;
import x.ovo.wechat.bot.core.message.TextMessage;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

@SuppressWarnings("unchecked")
public class EmoticonListener extends EventListener<MessageEvent<Message>, Message> {
    public EmoticonListener(Plugin plugin) {
        super(plugin);
    }

    @Override
    public boolean support(@NonNull MessageEvent<Message> messageMessageEvent, Message message) {
        return message instanceof TextMessage || message instanceof EmoteMessage;
    }

    @Override
    public boolean onEvent(@NonNull MessageEvent<Message> messageMessageEvent, Message message) {
        String content = message.getContent();
        Contactable from = message.getFrom();
        AtomicBoolean flag = new AtomicBoolean(false);

        // 群聊内艾特机器人消息
        if (message.isGroup() && message instanceof TextMessage textMessage && textMessage.isAtMe()) {
            from.sendEmoticon("");
            return true;
        }

        // 如果消息是图片表情消息且不是群聊消息，则返回表情的md5
        if (message instanceof EmoteMessage emoteMessage && !message.isGroup()) {
            from.sendMessage(emoteMessage.getMd5());
            return true;
        }

        if (this.plugin.<List<String>>getConfig().getOrDefault("blacklist", List.of()).stream().anyMatch(content::contains)) {
            return false;
        }
        // 处理content
        String s = content.replaceAll("@.* ", "").replaceAll("「.*」<br/>- - - - - - - - - - - - - - -<br/>", "");
        List<Map<String, Object>> data = this.plugin.<List<Map<String, Object>>>getConfig().getOrDefault("data", List.of());
        // 遍历data列表，找出包含关键词的item
        data.forEach(item -> ((List<String>) item.get("keywords")).stream()
                .filter(s::contains)
                .forEach(keyword -> {
                    ((List<String>) item.get("md5")).forEach(from::sendEmoticon);
                    flag.set(true);
                })
        );
        return flag.get();
    }

    @Override
    public boolean executeNext() {
        return false;
    }
}
